package org.elip.stewiemaze.server;

import java.util.ArrayList;
import java.util.List;

public class FormValidator {
	
	private static int index = 0;
	
	private static int MAXIMUM_CACHE_SIZE = 100; 
	
	private static List<String> NICKNAMES_CACHE = new ArrayList<String>();
	
	public static synchronized List<String> validateForm(String nickname, String email, String password) {
		
		List<String> errors = new ArrayList<String>();
		
		if (nickname.equals("")) {
			errors.add("Nickname must not be empty");
		}
		if (!email.equals("")) {
			if (!email.contains("@")) errors.add("You have enetered an invalid email");
		}
		if (NICKNAMES_CACHE.contains(nickname)) {
			errors.add("Sorry, this nickname is already taken");
		}
		else {
			if (DatastoreHelper.getPlayer(nickname) != null) {
				errors.add("Sorry, this nickname is already taken");
			}
		}
		if (errors.size() == 0) {
			if (NICKNAMES_CACHE.size() == MAXIMUM_CACHE_SIZE) {
				NICKNAMES_CACHE.remove(index % MAXIMUM_CACHE_SIZE);
				index++;
			}
			NICKNAMES_CACHE.add(nickname);
		}
		return errors;
	}

}
